﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Web.Mvc.ModelBinding;

namespace MvcApplicationBindersSample.Binders {
    public class ReadOnlyCollectionModelBinder<T> : IExtensibleModelBinder {

        public bool BindModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext) {
            // Simply reroute this to the IList<T> binder.
            ExtensibleModelBindingContext listBindingContext = new ExtensibleModelBindingContext(bindingContext) {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(IList<T>)),
                ModelName = bindingContext.ModelName
            };
            IExtensibleModelBinder listBinderProvider = bindingContext.ModelBinderProviders.GetBinder(controllerContext, listBindingContext);
            bool retVal = listBinderProvider.BindModel(controllerContext, listBindingContext);

            // create the ReadOnlyCollection<T>
            IList<T> list = listBindingContext.Model as IList<T>;
            bindingContext.Model = (list != null) ? new ReadOnlyCollection<T>(list) : null;

            // replace the original validation node and return
            bindingContext.ValidationNode = listBindingContext.ValidationNode;
            return retVal;
        }

    }
}
